<template>
<div class="layout-app">
	<!-- main -->
		<!-- 新增 -->
	<div class="addAcc">
		<el-dialog :title="dialogTitle" v-dialogDrag :visible.sync="dialogFormVisible" width="70%" :before-close="handleAddClose" :modal="false">
			<el-divider></el-divider>
			<!-- tabs -->
			<div class="tabs">
				<el-tabs type="border-card" v-model="activeTab" @tab-click="handleTabChange">
					<el-tab-pane label="基本信息[F2]" name="a">
						<div class="tabsMain">
							<!-- tabs-left -->
							<div class="tabs-left">
								<!-- 表单 -->
								<el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="90px" size="mini" :disabled="disabled">
								<el-row :gutter="20">
									  <el-col :span="v.spanRows" type="flex" v-for="(v,i) in formType" :key="i">
										  <!-- input -->
										  <el-form-item v-if="v.type == 'input'" :label="v.label" :prop="v.modelValue">
											<el-input v-if="v.zdy" v-autoCode="addForm.userCode" :suffix-icon='v.prefix' v-model="addForm.userCode" :disabled="v.disabled" placeholder="请输入内容"></el-input>
											<el-input v-else v-model="$data.addForm[v.modelValue]" @blur="inputChance(v,i)"></el-input>
										  </el-form-item>
										  <!-- cascader -->
										  <el-form-item v-if="v.type == 'cascader'" :label="v.label" :prop="v.modelValue">
											<el-cascader
											 :props="props"
											 v-model="addForm.nativePlace"
											 placeholder="请选择地区"
											 @change="handleSelectCost"
											>
											</el-cascader>
										  </el-form-item>
										  <!-- select -->
										  <el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
											<el-select v-model="$data.addForm[v.modelValue]" filterable 
											placeholder="请选择" @change="scname(v,i)">
												<el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id"> 
												<span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
											</el-select>
										  </el-form-item>
										  <!-- clinicId --> <!-- 确保禁用状态绑定 -->
										 <el-form-item v-if="v.type == 'clinicId'" :label="v.label" :prop="v.modelValue">
										   <el-select 
										     v-model="$data.addForm[v.modelValue]" 
										     filterable 
										     placeholder="请选择" 
										     @change="handleCId"
										     :disabled="v.disabled" 
										   >
										     <el-option 
										       v-for="item in $data[v.op]" 
										       :key="item.id" 
										       :label="item.label" 
										       :value="item.id"
										     > 
										       <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
										     </el-option>
										   </el-select>
										 </el-form-item>
										  <!-- date -->
										  <el-form-item v-if="v.type == 'date'" :label="v.label" :prop="v.modelValue">
											<el-date-picker class="autoWidth" :picker-options="pickerOptions" @focus="testDate(v,i)" @change="changDate"
											type="date" placeholder="选择日期" v-model="$data.addForm[v.modelValue]"></el-date-picker>
										  </el-form-item>
									  </el-col>
									</el-row>
								</el-form>
							</div>
							<!-- tabs-right -->
							<div class="tabs-right">
								<div class="main">
									<!-- 第一个表格隶属科室 -->
									<div class="mainOne">
										<!-- 修改header部分 -->
										<div class="header">
										  <div><span style="font-size: 12px;color: #fff;">隶属科室</span></div>
										  <div>
										    <el-button 
										      v-for="(v,i) in headerBtn" 
										      :key="i" 
										      :type="v.type" 
										      :icon="v.icon" 
										      size="mini"
										      @click="v.click(v.title === '编辑' || v.title === '删除' ? tableData[i-1] : i)"
										      style="color: #fff;"
										    >
										      {{ v.title }}
										    </el-button>
										  </div>
										</div>
										
										<!-- 修改表格部分，移除操作列 -->
										<!-- 修改表格部分，添加行点击事件和选中样式 -->
										<el-table 
										  :data="tableData" 
										  border
										  @row-click="handleRowClick"
										  :row-class-name="tableRowClassName"
										>
										  <el-table-column 
										    v-for="(col, inx) in tableRows" 
										    :key="inx" 
										    :type="col.type" 
										    :prop="col.prop" 
										    :label="col.name">
										  </el-table-column>
										  <!-- 保留固定列 -->
										  <el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
										</el-table>
									</div>
								</div>
							</div>
						</div>
					</el-tab-pane>
					<el-tab-pane label="岗位管理[F3]" name="b">
					  <div class="addFormB">
					    <!-- 表单 -->
					    <el-form ref="addFormB" :rules="addFormRules" :model="addForm" label-width="128px" size="mini">
					      <el-row :gutter="20">
					        <el-col :span="v.spanRows" type="flex" v-for="(v,i) in formTypeB" :key="i">
					          <!-- 角色权限项只在新增模式下显示 -->
					          <el-form-item v-if="v.type == 'chekedBox' && showRoleItem" :label="v.label" :prop="v.modelValue">
					            <el-select style="width: 178px;" v-model="addForm.roleId" placeholder="请选择" multiple collapse-tags @focus="chooserole">
					              <el-option v-for="item in $data[v.op]" :key="item.label" :label="item.label" :value="item.id"></el-option>
					            </el-select>
					          </el-form-item>
					          <!-- 其他表单项 -->
					          <template v-else>
					            <!-- input -->
					            <el-form-item v-if="v.type == 'input'" :label="v.label" :prop="v.modelValue">
					              <el-input :suffix-icon='v.prefix' v-model="$data.addForm[v.modelValue]" placeholder="请输入内容"></el-input>
					            </el-form-item>
					            <!-- select -->
					            <el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
					              <el-select v-model="$data.addForm[v.modelValue]" placeholder="请选择" @change="scname(v,i)" filterable >
					                <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id"> 
					                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
					              </el-select>
					            </el-form-item>
					            <!-- date -->
					            <el-form-item v-if="v.type == 'date'" :label="v.label" :prop="v.modelValue">
					              <el-date-picker class="autoWidth" :picker-options="pickerOptions" type="date" placeholder="选择日期" v-model="$data.addForm[v.modelValue]"
					               @focus="testDate(v,i)" @change="changDate"></el-date-picker>
					            </el-form-item>
					          </template>
					        </el-col>
					      </el-row>
					    </el-form>
					  </div>
					</el-tab-pane>
					<el-tab-pane label="简介" name="d">
						<addAccIntruce @children="getValue"></addAccIntruce>
					</el-tab-pane>
				</el-tabs>
			</div>
		  <div slot="footer" class="dialog-footer" v-if="watch == false">
			<el-button size="mini" type="primary" @click="addNewDiction" :loading="loading">添加</el-button>
			<el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
		  </div>
		  <div slot="footer" class="dialog-footer" v-if="showEdit == false">
				<el-button size="mini" type="primary" @click="saveEditData">保存</el-button>
				<el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
		  </div>
		</el-dialog>
		<!-- 新增科室Model -->
		<div class="main">
			<!-- 新增隶属科室dialog -->
			<el-dialog :title="nameTitle" v-dialogDrag :visible.sync="ksDialog" width="28%" :modal="false" :before-close="handleAddClose">
				<el-divider></el-divider>
				<!-- tabs -->
				<div class="tabs">
					<div class="tabsMain" style="padding: 12px;">
						<!-- 表单 -->
						<el-form ref="form" :model="addKsForm" label-width="120px" size="mini">
							<el-row :gutter="20">
							  <el-col :span="v.spanRows" type="flex" v-for="(v,i) in formKsType" :key="i">
								  <!-- select -->
								  <el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
									<span slot="label"> {{ v.label }} <span v-if="v.im == true" style="color: brown;">*</span></span>
									<el-select v-model="$data.addKsForm[v.modelValue]" @change="sksName" placeholder="请选择">
									    <el-option v-for="(item,index) in $data[v.op]" :key="index" :label="item.label" :value="item"> 
											<template>
												<span slot="label">{{ item.label }}</span>
												<span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
											</template>
										</el-option>
									</el-select>
								  </el-form-item>
							  </el-col>
							</el-row>
						</el-form>
					</div>
				</div>
			  <div slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="addNewKs" :loading="loading" :disabled="addBtn">添加</el-button>
				<el-button size="mini" @click="ksDialog = false">取消</el-button>
			  </div>
			</el-dialog>
		</div>
	</div>
</div>
</template>

<script>
// self
import AccType from './AccType.js'
import country from './country.js'
// prop
import addAccTable from './addAccTable.vue'
import addAccStations from './addAccStations.vue'
import addAccIntruce from './addAccIntruce.vue'
// ext
import { getLunar } from 'chinese-lunar-calendar'

// 接口
import { getArea,getArea2,getArea3,addStaff,getStaff,updateStaff,findAttribute,roleList } from "@/api/user.js";
// 接口
import { dict } from "@/api/staff/staff.js";
import { docclinic } from "@/api/cinic/cinic.js";
export default {
	inject: ['reload'], // 无痕刷新
	components:{
		AccType,
		addAccTable,addAccStations,addAccIntruce,
		country,
	},
	data(){
		return{
			//str
			value:'',
			deptCode:'',
			getLunarDay: '',
			dialogTitle:'',
			areaCode:'',
			areaPName:'',
			idx:'',
			year: new Date().getFullYear(),
			month: new Date().getMonth() + 1,
			date: new Date().getDate(),
			lunarDate: '',//农历
			// 1 - 3
			activeTab:'a',
			firstName:'',
			seconedName:'',
			thirdName:'',
			nameTitle:'',
			//num
			pageNum: 1, //当前页currentPage
			pageSize: 8,
			//ble
			loading:false,
			watch:true,
			showEdit:false,
			isedit:true,
			disabled:true,
			ksDialog:false,
			dialogFormVisible:false,
			addBtn:true,
			//arr
			formType:[],
			roleoptions:[], //角色信息选择
			jsOptions:[{id:1,label:'精神一类'},{id:2,label:'精神二类'}], // 精神权限
			ssOptions:[{id:1,label:'一级'},{id:2,label:'二级'},{id:3,label:'三级'},{id:4,label:'四级'}], // 手术权限
			idType:[],//证件类型
			institutionId: '', // 存储机构ID
			showInstitutionId: true, // 控制是否显示 institutionId 选项
			clinicId: '', // 存储当前诊所ID
			stateOptions:[{id:'0',label:'禁用'},{id:'1',label:'可用'}],//有效状态
			// title右侧按钮
			// 新增选中行数据
			selectedRow: null,
			// 修改headerBtn定义
			headerBtn: [
				{ 
			        add: "add", 
			        title: "", 
			        type: "text", 
			        icon: "el-icon-plus",
			        click: (i) => this.handClick(i)
				},
				{ 
			        adit: "adit", 
			        title: "", 
			        type: "text", 
			        icon: "el-icon-edit",
			        click: () => this.handleEdit()
				}, 
				{ 
			        del: "del", 
			        title: "", 
			        type: "text", 
			        icon: "el-icon-delete",
			        click: () => this.handleDelete()
				}
			],
			sexOptions:[{id:0,label:'未知'},{id:1,label:'男'},{id:2,label:'女'},{id:9,label:'保密'}],
			nationality:[{id:1,label:'中国'}], //国籍
			marryiedOptions:[],
			mjOptions:[], // 所学专业
			xlOptions:[], // 学历
			clincOptions:[], // 隶属诊所
			deptOption:[], // 科室
			nativeOptions:[], // 籍贯
			// 新增控制变量
			showRoleItem: true,
			YNOptions:[{id:1,label:'是'},{id:0,label:'否'}],
			statusOptions:[{id:1,label:'是',value:'重要科室'},{id:0,label:'否',value:'重要科室'}],
			antcOptions:[{id:0,label:'否'},{id:1,label:'一级抗生素'},{id:2,label:'二级抗生素'},{id:3,label:'三级抗生素'}],
			bloodOptions:[],
			PoliticalOptions:[
				{id: 0, "label": "中共党员"},{id: 2,"label": "中共预备党员"},{id: 3,"label": "共青团员"},{id: 4,"label": "民革党员"},
				{id: 5,"label": "民盟盟员"},{id: 6, "label": "民建会员"},{ id: 7,"label": "民进会员"},{id: 8,"label": "农工党党员"},
				{id: 9,"label": "致公党党员"},{id: 10,"label": "九三学社社员"},{id: 11,"label": "台盟盟员"},{id: 12,"label": "无党派人士"},{id: "13","label": "群众"},
			],
			// 表单验证规则 header
			addFormRules:{
				fullName: [{ required: true, message: '请输入员工姓名！', trigger: 'blur' }],
				idType: [{ required: true, message: '请选择证件类型！', trigger: 'change' }],
				standardCode: [{ required: true, message: '请填写医保编码！', trigger: 'blur' }],
				standardName: [{ required: true, message: '请填写医保名称！', trigger: 'blur' }],
				// 初始时不设为必填
				prescriptionRights: [],
				anesthesiaAuthorization: [],
				idNumber: [{required: true, pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号码', trigger: ['blur', 'change']}],
				contactNumber: [{required: true, pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: '请输入正确的11位手机号码', trigger: ['blur', 'change']}]
			},
			// obj
			addKsForm:{
				deptName:'',
				deptId:'',
				mainDep:'是',
				// specialtyName:'',
			},
			formKsType:[
				{ id:0, label:'隶属科室：',spanRows:24,type:'select',modelValue:'deptName',prefix:'el-icon-require',im:true,placeholder:'',op:'deptOption' },
				{ id:1, label:'主要科室：',spanRows:24,type:'select',modelValue:'mainDep',prefix:'el-icon-require',im:false,placeholder:'',op:'statusOptions' },
			],
			result:{},
			//obj
			provinceMap:{}, //存储三级联动城市籍贯
			pickerOptions: {
			  shortcuts: [
				{ text: '今天', onClick(picker) { picker.$emit('pick', new Date()); }}, 
				{ text: '昨天', onClick(picker) { const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24);picker.$emit('pick', date);}}, 
				{ text: '一周前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', date);}},
				{ text: '最近一个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);picker.$emit('pick', date);}},
				{ text: '最近三个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);picker.$emit('pick', date);}},
				{ text: '半年前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 180);picker.$emit('pick', date);}},
				{ text: '去年',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 360);picker.$emit('pick', date);}},
				]
			},
			depMap:{
				0: '否',
				1: '是',
			},
			addForm:{
				status:'1',
				userCode: "", //编码
				// fullNane: "001",//姓名
				fullName: "",//姓名
				idType:1,//身份证类型id
				idTypeName:"",//身份证类型
				idNumber: "", //身份证号码
				sex: "",//性别
				dateOfEmp: "",//工作日期
				birthDate: "",//出生日期
				lunarBirthDate: "", //农历出生日期
				minZu:"", //民族
				nationality:1,//国籍
				nativePlace:"",//籍贯
				maritalStatus:"", //婚姻状况 1:未婚 2:已婚 3:离异
				politicalStatus:"",//政治面貌
				bloodType:"",//血型
				contactNumber:'',//联系电话
				contactAddress:'',//联系地址
				entryTime:'2025-01-18',//入职时间
				institutionId:"",//隶属机构
				clinicId:'',// 当前诊所id
				contactAddress:'',//联系地址
				nativePlace:'',//户籍地址 = 籍贯
				standardCode:'',//贯标编码
				standardName:'',//贯标名称
				standardName:'',//贯标名称
				//2
				deptList:[],
				educationalBackground:'',//学历
				major:'',//所学专业
				professionalTitle:'',//专业职称
				qualificationNumber:'',//资格证号
				practiceDate:'',//职业日期
				prescriptionRights:'',//处方权
				chPrescriptionRights:'',//中药处方权
				anesthesiaAuthorization:'',//麻药权限
				surgicalPermission:'',//手术权限
				spiritPermission:'',//精神权限
				poisonPermission:'',//毒药权限
				antiTumorPermission:0,//抗肿瘤药物权限
				antibioticAuthorization:0, // 抗生素等级
				roleId:[],
				//3
				signatureImage:'',//手工签名照片
				workIdPhoto:'',//工作证件照
				pcElectronicImage:'',//执业证电子图片
				qcElectronicImage:''//资格证电子图片
			},
			formTypeB:[],
			options:[],
			professionalOptions:[],
			MZOptions:[],
			tableData:[],
			tableRows:[{ name:"科室名称", prop:"deptName", type:"" },{ name:"主要科室", prop:"mainDep", type:"" }],
			// props
			props: {
				lazy: true,
				lazyLoad: (node, resolve) => {
				  const { level } = node;
				  if (level == 0) {
					this.getCostTypeOption(node).then((res) => { resolve(res) });
				  } else if (level == 1) {
					this.getCostOption(node).then((res) => { resolve(res) });
				  } else if (level == 2) {
					this.getCostOptionIII(node).then((res) => { resolve(res) });
				  }	else {
					this.getCostOptionIII(node).then((res) => { resolve(res) });
				  }
				},
			},
		}
	},
	mounted() {
	  // 获取字典数据
	  this.getditc();
	  // 检查institutionId并设置相关状态
	  this.checkInstitutionId();
	  // 根据是否编辑状态初始化formTypeB
	    this.updateFormTypeB();
	  // 左侧提交表单
	  this.formType = AccType.map(function(v) { 
	    // 如果是"当前诊所："字段，根据情况设置disabled
	    if (v.label === '当前诊所：' || v.type === 'clinicId') {
	      return {
	        ...v,
	        disabled: this.institutionId !== 0 // 当clinicId不为0时禁用
	      };
	    }
	    return v;
	  }.bind(this)).filter(Boolean).slice(0,21);
	  
	  this.getInstitutionId();
	  this.formTypeB = AccType.map(function(val) { return val }).slice(21,34);
	},
	methods:{
		// 字典数据
		async getditc(){
		   this.result = await dict();
		   // console.log(this.result.data);
		   // 设置本地存储
		   localStorage.setItem('dict', JSON.stringify(this.result.data));
		   //  证件类型
		   this.idType = this.result.data.certypeEntities.map(v=>{ return { label: v.name , ...v }});
		   //  民族
		   this.MZOptions = this.result.data.natyEntities.map(v=>{ return { label: v.name , ...v }})
		   //  专业职称
		   this.professionalOptions = this.result.data.profttlEntities.map(v=>{ return { label: v.name , ...v }})
		   // 所学专业
		   this.mjOptions = this.result.data.jobEntities.map(v=>{ return { label: v.name , ...v }})
		   // 学历
		   this.xlOptions = this.result.data.edulBacdEntities.map(v=>{ return { label: v.name , ...v }})
		   //  婚姻状况
		   this.marryiedOptions = this.result.data.mrgStateEntities.map(v=>{ return { label: v.name , ...v }})
		   //  血型
		   this.bloodOptions = this.result.data.aboTypeEntities.map(v=>{ return { label: v.name , ...v }})
		   // 暂时过滤掉RH阴性和RH阳性的选项
		   this.bloodOptions = this.bloodOptions.filter(item =>
		     item.name !== 'RH阳性' && item.name !== 'RH阴性'
		   );
		  
		},
		sksName(v){
			console.log(v,'vvvvvvv');
			if(v.value == '重要科室'){
				this.addKsForm.mainDep = v.label;
				this.addBtn = false; // 取消禁用
			}else{
				this.addKsForm.deptId = v.id;
				this.addKsForm.deptName = v.label;
				this.addBtn = false;
			}
		},
		// 表格行选中事件
		handleRowClick(row) {
		    this.selectedRow = row;
		},
		// 编辑方法修改
		handleEdit() {
		    if (!this.selectedRow) {
		      this.$message.warning('请先选择要编辑的行数据');
		      return;
		    }
		    
		    this.nameTitle = '编辑';
		    this.ksDialog = true;
		    this.editingRow = this.selectedRow;
		    this.addKsForm = JSON.parse(JSON.stringify(this.selectedRow));
		},
		// 检查institutionId并设置相关状态
		checkInstitutionId() {
		  // 从本地存储获取userInfo
		  const userInfo = JSON.parse(localStorage.getItem('userInfo'));
		  
		  if (userInfo) {
		    this.institutionId = userInfo.clinicId || 0;
		    
		    // 更新表单类型中的禁用状态
		    this.formType = this.formType.map(item => {
		      if (item.label === '当前诊所：' || item.type === 'clinicId') {
		        return {
		          ...item,
		          disabled: this.institutionId !== 0 // 当clinicId不为0时禁用
		        };
		      }
		      return item;
		    });
		    
		    // 当clinicId为0时，显示并允许选择诊所
		    if (this.institutionId == 0) {
		      this.showInstitutionId = true;
		      this.getInstitutionId();
		      
		      // 初始时禁用新增按钮，直到选择了诊所
		      this.disableAddDeptButton();
		    } else {
		      // 当clinicId不为0时，显示但禁用当前诊所选项
		      this.showInstitutionId = true;
		      this.addForm.clinicId = this.institutionId;
		      this.clinicId = this.institutionId;
		      
		      // 启用新增隶属科室按钮
		      this.enableAddDeptButton();
		    }
		  }
		},
		// 新增方法用于更新formTypeB
		  updateFormTypeB() {
		    // 如果是编辑状态，过滤掉角色权限项
		    if (!this.showEdit) {
		      this.formTypeB = AccType.map(function(val) { return val })
		        .slice(21,34)
		        .filter(item => item.modelValue !== 'roleId');
		      this.showRoleItem = false;
		    } else {
		      this.formTypeB = AccType.map(function(val) { return val }).slice(21,35);
		      this.showRoleItem = true;
		    }
		  },
		// 表格行样式
		  tableRowClassName({row}) {
		    return row === this.selectedRow ? 'selected-row' : '';
		  },
		// 禁用新增隶属科室按钮
		disableAddDeptButton() {
		  this.headerBtn[0].disabled = true; // 禁用新增按钮
		  this.headerBtn[0].title = "请先选择诊所"; // 修改提示文字
		},
		
		// 启用新增隶属科室按钮
		enableAddDeptButton() {
		  this.headerBtn[0].disabled = false; // 启用新增按钮
		  this.headerBtn[0].title = ""; // 恢复默认文字
		},

		// 处理 institutionId 变化
		handleInstitutionChange(val) {
		  this.clinicId = val;
		  this.addForm.institutionId = val;
		  this.addForm.clinicId = val;
		  
		  if (val) {
		    this.enableAddDeptButton();
		    this.getKs(val); // 获取科室数据
		  } else {
		    this.disableAddDeptButton();
		  }
		},
		  // 获取赋值隶属机构
		  async getInstitutionId(){
		  	let res = await docclinic();
		  	this.clincOptions = res.data.map(v=>{ return {label:v.name,...v} });
		  },
		  
		// SelectVal to editForm
		handleCId(val){
			this.clinicId = this.addForm.institutionId = val;
		},
		scname(v, i) {
			// console.log(v,i,'ooooooooooo');
		  // 如果是专业职称字段变化
		  if (v.modelValue === 'professionalTitle') {
		    // 检查选中的是否是特定职称
		    const selectedTitle = this.professionalOptions.find(item => item.id === this.addForm.professionalTitle);
			
		    const requiredTitles = ['医师', '主任医师', '主治医师', '副主任医师'];
		    
		    if (selectedTitle && requiredTitles.includes(selectedTitle.label)) {
		      // 设置处方权和麻药权限为必填
		      this.addFormRules.prescriptionRights = [
		        { required: true, message: '请选择处方权！', trigger: 'blur' }
		      ];
		      this.addFormRules.anesthesiaAuthorization = [
		        { required: true, message: '请选择麻药权限！', trigger: 'blur' }
		      ];
		    } else {
		      // 如果不是特定职称，取消必填
		      this.addFormRules.prescriptionRights = [];
		      this.addFormRules.anesthesiaAuthorization = [];
		    }
		    
		    // 强制更新表单验证规则
		    this.$nextTick(() => {
		      if (this.$refs.addForm) {
		        this.$refs.addForm.clearValidate(['prescriptionRights', 'anesthesiaAuthorization']);
		      }
		    });
		  }
		},

		// 新增/编辑保存科室
		// addNewKs() {
		//   // 检查是否已存在主要科室（排除当前编辑的行）
		//   const hasMainDept = this.tableData.some(item => 
		//     item.mainDep === '是' && 
		//     (this.nameTitle !== '编辑' || item !== this.editingRow)
		//   );
		  
		//   // 如果当前设置为主要科室且已存在主要科室
		//   if (this.addKsForm.mainDep === '是' && hasMainDept) {
		//     this.$message.error('主要科室只能有一个，请修改后再添加！');
		//     return;
		//   }
		
		//   this.loading = true;
		  
		//   if (this.nameTitle === '编辑') {
		//     // 编辑模式逻辑
		//     setTimeout(() => {
		//       if (this.editingRow) {
		//         // 更新原行数据
		//         Object.assign(this.editingRow, JSON.parse(JSON.stringify(this.addKsForm)));
		        
		//         // 编辑完成后检查是否有主要科室
		//         const hasMainAfterEdit = this.tableData.some(item => item.mainDep === '是');
		//         if (!hasMainAfterEdit) {
		//           this.$message({ 
		//             type: 'error', 
		//             message: '隶属科室中必须有一个主要科室！'
		//           });
		//           this.loading = false;
		//           return;
		//         }
		        
		//         // 如果设置为"是"，取消其他科室的主要状态
		//         if (this.editingRow.mainDep === '是') {
		//           this.tableData.forEach(item => {
		//             if (item !== this.editingRow) {
		//               item.mainDep = '否';
		//             }
		//           });
		//         }
		        
		//         this.$message.success('修改成功！');
		//       } else {
		//         this.$message.error('编辑数据无效！');
		//       }
		      
		//       this.loading = false;
		//       this.ksDialog = false;
		//       this.editingRow = null;
		//     }, 888);
		//   } else {
		//     // 新增模式逻辑
		//     setTimeout(() => {
		//       // 如果新增为"是"，取消其他科室的主要状态
		//       if (this.addKsForm.mainDep === '是') {
		//         this.tableData.forEach(item => {
		//           item.mainDep = '否';
		//         });
		//       }
		      
		//       // 如果没有主要科室，强制设置第一个新增的科室为主要科室
		//       if (this.tableData.length === 0) {
		//         this.addKsForm.mainDep = '是';
		//       }
		      
		//       this.tableData.push(JSON.parse(JSON.stringify(this.addKsForm)));
		//       this.loading = false;
		//       this.ksDialog = false;
		//       this.$message.success('添加成功！');
		//     }, 1500);
		//   }
		// },
		
		
		// 删除方法修改
		  handleDelete() {
		    if (!this.selectedRow) {
		      this.$message.warning('请先选择要删除的行数据');
		      return;
		    }
		    
		    const row = this.selectedRow;
		    const index = this.tableData.indexOf(row);
		    
		    // 检查是否要删除的是主要科室
		    if (row.mainDep === '是') {
		      // 检查是否是最后一个科室
		      if (this.tableData.length === 1) {
		        this.$message.error('需保留一个主要科室！');
		        return;
		      }
		      
		      this.$confirm('此科室为当前的重要科室！请谨慎删除', '警告', {
		        confirmButtonText: '确定删除',
		        cancelButtonText: '取消',
		        type: 'warning'
		      }).then(() => {
		        // 找到下一条数据并设置为主要科室
		        let nextIndex = index === this.tableData.length - 1 ? index - 1 : index + 1;
		        this.tableData[nextIndex].mainDep = '是';
		        
		        // 删除当前行
		        this.tableData.splice(index, 1);
		        this.selectedRow = null; // 清空选中
		        
		        this.$message.success('删除成功! 已自动设置下一条数据为主要科室');
		      }).catch(() => {
		        this.$message.info('已取消删除');
		      });
		    } else {
		      // 非主要科室直接删除
		      this.$confirm('确定要删除此科室?', '提示', {
		        confirmButtonText: '确定',
		        cancelButtonText: '取消',
		        type: 'warning'
		      }).then(() => {
		        this.tableData.splice(index, 1);
		        this.selectedRow = null; // 清空选中
		        this.$message.success('删除成功!');
		      }).catch(() => {
		        this.$message.info('已取消删除');
		      });
		    }
		  },
		// 编辑隶属科室
		// 编辑表格行数据
		editFormValue(row) {
		  this.nameTitle = '编辑';
		  this.ksDialog = true;
		  
		  // 保存当前编辑的行数据引用
		  this.editingRow = row;
		  
		  // 深拷贝当前行数据到表单
		  this.addKsForm = JSON.parse(JSON.stringify(row));
		  
		  console.log('正在编辑行数据', row);
		},
		
		// 打开model// 父组件控制打开新增模态框
		// 修改openModel方法
		  async openModel(param) {
		    console.log(param,'paramparamparamparam');
		    if(param == '新增') {
		      this.dialogFormVisible = true;
		      this.isShow = true;
		      this.showEdit = true;
		      this.watch = false;
		      this.disabled = false;
		      this.dialogTitle = '新增员工档案';
		      this.showRoleItem = true;
		      this.updateFormTypeB();
		      // 重置表单
		      this.resetAllForms();
		    } else if(param.nameTitle == '查看') {
		      this.dialogFormVisible = true;
		      this.watch = true;
		      this.showEdit = true;
		      this.isedit = false;
		      this.disabled = true;
		      this.dialogTitle = '查看员工档案';
		      this.showRoleItem = true;
		      this.updateFormTypeB();
		      let res = await getStaff({ id:param.id });
		      if(res.code === 200) {
		        // 遍历 res.data 的所有键名
		        for (let key in res.data) {
		          // 检查键名是否在对象 A 中存在
		          if (this.addForm.hasOwnProperty(key)) {
		            // 如果存在，将 B 中的值更新到 A 中
		            this.addForm[key] = res.data[key];
		          }
		        }
		        this.tableData = this.addForm.deptList;
		        this.addForm.id = param.id;
		      }
		    } else if(param.nameTitle == '修改') {
				this.dialogFormVisible = true;
				this.dialogTitle = '修改员工档案';
				this.showEdit = false;
				this.watch = true;
				this.disabled = false;
				this.showRoleItem = false;
				this.updateFormTypeB();
				
				// 获取完整员工数据
				let res = await getStaff({ id: param.id });
				if(res.code === 200) {
				  // 使用深拷贝赋值
				  this.addForm = JSON.parse(JSON.stringify(res.data));
				  
				  // 处理科室数据
				  this.tableData = this.addForm.deptList || [];
				  
				  // 处理角色数据
				  if(this.addForm.roleId) {
					this.addForm.roleId = Array.isArray(this.addForm.roleId) ? 
					  this.addForm.roleId : 
					  [this.addForm.roleId];
				  }
				  
				  // 设置编辑标志
				  this.isEdit = true;
				  this.editId = param.id;
				}
			  }
		  },
		// 触发角色信息选择
		async chooserole(){
		  // 角色信息数据源
			this.roleoptions = await roleList({
			   pageNum: this.pageNum,
			   pageSize: this.pageSize
			})
			this.roleoptions = this.roleoptions.map(v=>{
				return { label:v.roleName , ...v }
			})
		},
		// 步骤
		// 修改handClick方法
		handClick(i) {
		  // 只有当显示institutionId时才需要检查诊所选择
		  if (this.showInstitutionId && !this.addForm.clinicId && this.institutionId === 0) {
		    this.$message.warning('请先选择诊所');
		    return;
		  }
		  
		  // 只处理新增逻辑
		  if (i === 0) {
		    // 获取科室 - 如果隐藏了institutionId，使用当前用户的clinicId
		    const clinicIdToUse = this.showInstitutionId ? this.addForm.clinicId : this.institutionId;
		    this.getKs(clinicIdToUse);
		    
		    // 打开隶属科室model
		    this.ksDialog = true;
		    this.nameTitle = '新增隶属科室';
		    
		    // 在这里设置默认值
		    this.addKsForm = {
		      deptName: '',
		      deptId: '',
		      // 根据当前是否有科室决定默认值
		      mainDep: this.tableData.length === 0 ? '是' : '否'
		    };
		    this.addBtn = true; // 重置按钮状态
		  }
		},
		
		// 简化后的addNewKs方法
		// 修改addNewKs方法（简化编辑模式下的逻辑）
		  addNewKs() {
		    // 检查是否已存在相同科室名称或ID（仅新增时检查）
		    if (this.nameTitle !== '编辑') {
		      const isDeptExist = this.tableData.some(item => 
		        item.deptName === this.addKsForm.deptName || 
		        item.deptId === this.addKsForm.deptId
		      );
		      
		      if (isDeptExist) {
		        this.$message.error(this.addKsForm.deptName + '：已存在于表格列表之中，请添加新的科室');
		        return;
		      }
		    }
		    
		    this.loading = true;
		    
		    if (this.nameTitle === '编辑') {
		      // 编辑模式逻辑（不再检查主要科室，由外层方法检查）
		      setTimeout(() => {
		        if (this.editingRow) {
		          // 更新原行数据
		          Object.assign(this.editingRow, JSON.parse(JSON.stringify(this.addKsForm)));
		          this.$message.success('修改成功！');
		        } else {
		          this.$message.error('编辑数据无效！');
		        }
		        
		        this.loading = false;
		        this.ksDialog = false;
		        this.editingRow = null;
		      }, 888);
		    } else {
		      // 新增模式逻辑（保持原有检查）
		      const hasMainDept = this.tableData.some(item => item.mainDep === '是');
		      
		      if (this.addKsForm.mainDep === '是' && hasMainDept) {
		        this.$message.error('主要科室只能有一个，请修改后再添加！');
		        this.loading = false;
		        return;
		      }
		      
		      setTimeout(() => {
		        // 如果新增为"是"，取消其他科室的主要状态
		        if (this.addKsForm.mainDep === '是') {
		          this.tableData.forEach(item => {
		            item.mainDep = '否';
		          });
		        }
		        
		        this.tableData.push(JSON.parse(JSON.stringify(this.addKsForm)));
		        this.loading = false;
		        this.ksDialog = false;
		        this.$message.success('添加成功！');
		      }, 1500);
		    }
		  },
		// escansel
		// 获取省级名称选项
		getCostTypeOption(node) {
		  return new Promise((resolve, reject) => {
			getArea().then((res) => {
				// console.log(res);
				if (res.code == 200) {
				  let option = res.data.map((item) => {
					return {
					  label: item.areaName,
					  value: item.areaName,
					  leaf: node.level >= 1,
					};
				  });
				  resolve(option);
				}
			  })
			  .catch((err) => console.log(err));
		  });
		},
		// 获取市级名称选项
		async getCostOption(node) {
			return new Promise((resolve, reject) => {
			 getArea2({ areaLevel:2, areaPName: node.value}).then((res) => {
				if (res.code == 200) {
				  let option = res.data.map((item) => {
					return {
					  label: item.areaName,
					  value: item.areaName,
					  leaf: node.level >= 2,
					};
				  });
				  this.firstName = node.value;
				  console.log(node.value,'diyi');
				  resolve(option);
				} 
			  })
			  .catch((err) => console.log(err));
			});
		},
		// 获取区名称选项
		async getCostOptionIII(node) {
			console.log(node.value);
			node.value == '市辖区' ? this.firstName : node.value
			return new Promise((resolve, reject) => {
			 getArea3({ areaPName:this.firstName, areaLevel:3, areaCName: node.value}).then((res) => {
				if (res.code == 200) {
				  let option = res.data.map((item) => {
					return {
					  label: item.areaName,
					  value: item.areaName,
					  leaf: node.level >= 1,
					};
				  });
				  // console.log(option);
				  resolve(option);
				} 
			  })
			  .catch((err) => console.log(err));
			});
		},
		
		testDate(v,i){
			this.idx = v.id
		},
		// 时间处理
		changDate(val){
			let i = this.idx
			switch(i) {
				case 5:
				function formatDate(date) {
				  const year = date.getFullYear();
				  const month = (date.getMonth() + 1).toString().padStart(2, '0');
				  const day = date.getDate().toString().padStart(2, '0');
				  return `${year}-${month}-${day}`;
				}
				 
				// 使用示例
				const now = new Date();
				this.addForm.dateOfEmp = formatDate(val);
			}
		},
		handleSelectCost(val) {
		  this.addForm.nativePlace = val.join(',')
		},
		// testA(val){
		// 	console.log(val);
		// },
		inputChance(v,i){
			console.log(v,i);
			// i event
			switch (i) {
				case 3:
					// 同步赋值
					let birthday = "";
					let time = '';
					let sex = '';
					let age = '';
					let myDate = new Date()
					//根据身份证号码获取出生年月
					if (this.addForm.idNumber.length == 18) {
						this.areaCode = this.addForm.idNumber.substr(0, 6);
						this.year = this.addForm.idNumber.substr(6, 4);
						this.month = this.addForm.idNumber.substr(10, 2);
						this.date = this.addForm.idNumber.substr(12, 2);
						// console.log(this.year + '年',this.month+ 'yue',this.date+'日');
					    birthday = this.addForm.idNumber.substr(6, 8);
					    time = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
						this.addForm.birthDate = time
						// let dates = dayjs().format("YYYY/MM/DD");
						// 获取农历
						// console.log(time)
						this.getLunarDay = getLunar(this.year, this.month, this.date)
						this.addForm.lunarBirthDate = this.getLunarDay.dateStr
						// 农历	酆语梦 35021119780422570X 测试 
					}
					//根据身份证号码获取性别
					if (this.addForm.idNumber.length == 18) {
					  sex = this.addForm.idNumber.substr(16,1);
					  if(sex% 2 == 1){
					  this.addForm.sex = 1
					   } else {
					  this.addForm.sex = 2
					  }
					}
					break;
			}
		},
		// 科室属性
		async getKs(){
			// this.clinicId = ''
			console.log(this.clinicId,'this.clinicIdthis.clinicIdthis.clinicId');
			let res = await findAttribute({
				clinicId:this.clinicId
			})
			this.deptOption = res.data.map(v=>{
				return { id:v.id,label: v.deptName,value: v.deptName,specialtyName:v.specialtyName,remark:v.remark}
			});
			console.log(this.deptOption,'科室科室科室看是科室');
		},
		// 选项卡切换回调（可选）
		handleTabChange(tab) {
		  console.log('当前选项卡:', tab.name);
		},
		// 新增保存方法修改
		// 新增保存方法（保持不变）
		  async addNewDiction() {
		    // 检查是否有主要科室
		    const hasMainDept = this.tableData.some(item => item.mainDep === '是');
		    if (!hasMainDept) {
		      this.activeTab = 'a';
		      this.$message.error('隶属科室中必须有一个主要科室！');
		      return;
		    }
		    
		    console.log(this.addForm,'要传的参数新增');
		    this.addForm.deptList = JSON.parse(JSON.stringify(this.tableData));
		    this.addForm.userCode = JSON.parse(sessionStorage.getItem('deptCode'));
		    
		    this.$refs.addForm.validate(async(valid) => {
		      if(valid) {
		        if(this.addForm.deptList.length === 0) {
		          this.$message.error('隶属科室为必填项！');
		          this.activeTab = 'a';
		        } else {
		          this.loading = true;
		          try {
		            let rs = await addStaff(this.addForm);
		            if (rs.code === 200) {
		              this.$message.success(rs.message);
		              this.$refs.addForm.resetFields();
		              this.resetAllForms();
		              this.reload();
		              this.dialogFormVisible = false;
		            } else {
		              this.$message.error(rs.message);
		              this.gotodw(rs.message);
		            }
		          } finally {
		            this.loading = false;
		          }
		        }
		      } else {
		        this.activeTab = 'a';
		        this.$message.error('请填写完整表单！');
		      }
		    });  
		  },
		
		// 编辑保存方法修改
		// 修改保存编辑数据方法
		  async saveEditData() {
		    // 先检查是否有主要科室
		    const hasMainDept = this.tableData.some(item => item.mainDep === '是');
		    if (!hasMainDept) {
		      this.$message.error('隶属科室中必须有一个主要科室！');
		      this.activeTab = 'a'; // 切换到基本信息标签页
		      return;
		    }
		
		    // 验证表单
		    this.$refs.addForm.validate(async(valid) => {
		      if(valid) {
		        this.loading = true;
		        console.log(this.addForm,'要传的参数修改');
		        
		        try {
		          // 更新科室列表
		          this.addForm.deptList = JSON.parse(JSON.stringify(this.tableData));
		          
		          let rs = await updateStaff(this.addForm);
		          if (rs.code === 200) {
		            this.$message({
		              type: 'success',
		              message: rs.message,
		            });
		            this.$refs.addForm.resetFields();
		            this.resetAllForms();
		            this.reload();
		            this.dialogFormVisible = false;
		          } else {
		            this.$message.error(rs.message);
		          }
		        } finally {
		          this.loading = false;
		        }
		      }
		    });
		  },
		// 在父组件中添加 resetAllForms 方法
		resetAllForms() {
		  // 1. 重置主表单
		  if (this.$refs.addForm) {
		    this.$refs.addForm.resetFields();
		  }
		  
		  // 2. 重置选项卡B的表单
		  if (this.$refs.addFormB) {
		    this.$refs.addFormB.resetFields();
		  }
		  
		  // 3. 清空表格数据
		  this.tableData = [];
		  
		  // 4. 重置子组件
		  if (this.$refs.parMehod) {
		    this.$refs.parMehod.resetChildForm();
		  }
		  if (this.$refs.addAccIntruce) {
		    this.$refs.addAccIntruce.resetForm();
		  }
		  if (this.$refs.addAccTable) {
		    this.$refs.addAccTable.resetForm();
		  }
		  
		  // 5. 重置活动选项卡
		  this.activeTab = 'a';
		  
		  // 6. 重置文件上传组件
		  // this.resetFileUploads();
		  
		  // 7. 重置级联选择器
		  // this.resetCascader();
		},
		
		
		// 重置非表单数据的方法
		resetOtherData() {
		  // 重置表格数据
		  this.tableData = [];
		  
		  // 重置其他相关状态
		  this.editMode = false;
		  this.currentEditId = null;
		  this.dialogTitle = '新增员工档案';
		  
		  // 重置表单中的非绑定数据（如果有）
		  this.addForm = {
		    ...this.addForm,
		    deptList: [],
		    userCode: ""
		  };
		},

		// 简单错误定位
		gotodw(eoor){
			console.log(eoor,'eoor');
			if(eoor.includes('专业职称')){
				this.activeTab = 'b'
			}
		},

		// 控制科室属性新增model，接收子组件传递过来的值并赋值
		sonData(newVal){
			// console.log(newVal);
			// this.addForm.deptList = JSON.parse(JSON.stringify(newVal));
			console.log(newVal,'孙子组件传过来的');
		},
		//sons
		//接收父组件传过来的
		getValue(data) {
			console.log(data,'子组件3传过来的');
			if(data != ''){
				this.addForm.signatureImage = data.signatureImage
				this.addForm.workIdPhoto = data.workIdPhoto
				this.addForm.pcElectronicImage = data.pcElectronicImage
				this.addForm.qcElectronicImage = data.qcElectronicImage
			}
		},
		// getValue2(data) {
		// 	console.log(data,'子组件3.2传过来的');
		// 	if(data != ''){
		// 		this.addForm.workIdPhoto = data
		// 	}
		// },
		//接收父组件传过来的
		sonValue(data) {
			// console.log(data,'子2组件传过来的');
			if(data != ''){
				this.addForm = {...this.addForm, ...data};
				// this.addForm.push(...data)
			}
		  // this.addForm.push(JSON.parse(JSON.stringify(data)))
		},
		
		// 关闭
		handleAddClose(done) {
			done();
			this.resetAllForms(); // 调用优化后的重置方法
		},
	},
	
}
</script>

<style lang="less" scoped>
	/* 添加选中行样式 */
	/deep/ .el-table .selected-row {
	  background-color: #0071a5;
	  color: #fff;
	}
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
    .addAcc{
		/deep/ .el-dialog__header{
			padding: 12px;
			background-color: #007bb0;
		}
		/deep/ .el-dialog__title{
			font-size: 12px;
		}
		/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
			margin-bottom: 12px;
		}
		/deep/ .el-dialog__title{
			color: #fff;
		}
		/deep/ .el-dialog__headerbtn .el-dialog__close{
			color: #fff;
		}
		/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
			background-color: brown;
		}
		/deep/ .el-dialog__body{
			padding: 0;
		}
		/deep/ .el-divider--horizontal{
			margin: 0;
		}
		
		// self
		// 选项卡
		.tabs{
			
			.tabsMain{
				display: flex;
				border: 1px solid #f4f4f4;
				.tabs-left{
					flex: 1;
					padding:12px;
					border: 1px solid #e8f0ee;
					// date flex
					.autoWidth{
						width: 100%; /* 设置宽度为100% */
					}
					/deep/ .el-input__icon{
						color: brown;
					}
					/deep/ .el-form-item__label{
						display: flex;
						justify-content: right;
						font-size: 12px;
					}
					/deep/ .el-input--mini .el-input__inner{
						height: 26px;
						line-height: 26px;
					}
				}
				.tabs-right{
					flex: 1;
					padding:12px;
					margin-left: 8px;
					border: 1px solid #e8f0ee;
						.header{
							display: flex;
							justify-content: space-between;
							align-items: center;
							background-color: #007bb0;
							padding: 4px;
						}
						.main{
							height: 100%;
							display: flex;
							flex-direction: column;
							justify-content: space-between;
							.mainOne{
								flex: 1;
								height: 100%;
								border: 1px solid #007bb0;
							}
					}
				}
			}
			.addFormB{
				padding:12px;
				border: 1px solid #e8f0ee;
				// date flex
				.autoWidth{
					width: 100%; /* 设置宽度为100% */
				}
				/deep/ .el-input__icon{
					color: brown;
				}
				/deep/ .el-form-item__label{
					display: flex;
					justify-content: right;
					font-size: 12px;
				}
				/deep/ .el-input--mini .el-input__inner{
					height: 26px;
					line-height: 26px;
				}
			}
			
		}
	}
}
</style>